﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RaytracerLib.Layers;
using RaytracerLib.MathLib;

namespace RaytracerLib.Layers.Interpolators
{
    public class BilinearInterpolator : Interpolator
    {
        public BilinearInterpolator(ArrayBase a_array)
            : base(a_array)
        {
        }

        public override ColorFloat InterpolateColor(double a_x, double a_y)
        {
            double a = a_x - (int)a_x - 0.5;
            double b = a_y - (int)a_y - 0.5;

            if (a >= 0)
                a = 1 - a;
            else
                a = -a;

            if (b >= 0)
                b = 1 - b;
            else
                b = -b;

            int x1 = (int)(a_x - 0.5);
            int y1 = (int)(a_y - 0.5);

            if (a_x < 0.5)
                x1--;
            if (a_y < 0.5)
                y1--;

            int x2 = OverlayCorrector.CorrectX(x1 + 1);
            int y2 = OverlayCorrector.CorrectY(y1 + 1);

            x1 = OverlayCorrector.CorrectX(x1);
            y1 = OverlayCorrector.CorrectY(y1);

            return m_array.GetColor(x1, y1) * a * b +
                   m_array.GetColor(x2, y1) * (1 - a) * b +
                   m_array.GetColor(x1, y2) * a * (1 - b) +
                   m_array.GetColor(x2, y2) * (1 - a) * (1 - b);
        }

        public override double InterpolateValue(double a_x, double a_y)
        {
            double a = a_x - (int)a_x - 0.5;
            double b = a_y - (int)a_y - 0.5;

            if (a >= 0)
                a = 1 - a;
            else
                a = -a;

            if (b >= 0)
                b = 1 - b;
            else
                b = -b;

            int x1 = (int)(a_x - 0.5);
            int y1 = (int)(a_y - 0.5);

            if (a_x < 0.5)
                x1--;
            if (a_y < 0.5)
                y1--;

            int x2 = OverlayCorrector.CorrectX(x1 + 1);
            int y2 = OverlayCorrector.CorrectY(y1 + 1);

            x1 = OverlayCorrector.CorrectX(x1);
            y1 = OverlayCorrector.CorrectY(y1);

            return m_array.GetValue(x1, y1) * a * b +
                   m_array.GetValue(x2, y1) * (1 - a) * b +
                   m_array.GetValue(x1, y2) * a * (1 - b) +
                   m_array.GetValue(x2, y2) * (1 - a) * (1 - b);
        }
    }
}
